package com.example.testone

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.example.testone.databinding.FragmentMainBinding
import com.example.testone.utils.MyLog
import com.example.testone.utils.MySerialPort
import com.example.testone.utils.SerialPortUtils
import com.example.testone.viewModels.SettingViewModel
import dagger.hilt.android.AndroidEntryPoint
import me.f1reking.serialportlib.SerialPortHelper
import javax.inject.Inject

@AndroidEntryPoint
class MainFragment : Fragment() {
    val TAG = "NavMainFragment"
    var switchState = 1
    lateinit var binding:FragmentMainBinding

    @Inject
    lateinit var serialPortUtil: SerialPortUtils
//
    @Inject
    lateinit var mySerialPort: MySerialPort

    val viewModel: SettingViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //发起开机指令
//        viewModel.isOpening = false
//        viewModel.settingRunningState.value = 1



    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {




        binding = FragmentMainBinding.inflate(inflater,container,false)
        binding.viewModel = viewModel
        binding.lifecycleOwner = this

        binding.testImg.setOnClickListener {
            var buffer = byteArrayOf(0x20,0x21,0x1E,0x3C,0x00, 0x9B.toByte())
            if(switchState==1){
//                mySerialPort.serialPort.close()
                switchState = 2
//                MyLog.print(MySerialPort.TAG,"关闭")
//                viewModel.settingRunningState.value=2
            }else{
//                mySerialPort.serialPort.open()
//                MyLog.print(MySerialPort.TAG,"开启")
                buffer = byteArrayOf(0x20,0x22,0x00,0x00,0x00, 0x42.toByte())
                switchState =1
//                viewModel.settingRunningState.value=1
            }
            val state = mySerialPort.serialPort.sendBytes(buffer)
//            SerialPortUtil.sendByte(buffer)
//            serialPortUtil.sendMsg(buffer)
            MyLog.print(MySerialPort.TAG,"isOpen:${mySerialPort.serialPort.isOpen};state:${state}")
        }
        // Inflate the layout for this fragment
        return binding.root
    }


}